import type { UserInfo } from '@vben/types';

import type { AuthApi } from '#/api';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { StorageManager } from '@vben-core/shared/cache';

import { ElNotification } from 'element-plus';
// import jwt from 'jsonwebtoken';
import { defineStore } from 'pinia';

import { authApi, userApi } from '#/api';
import { $t } from '#/locales';

const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});
function parseJWT(token: any) {
  const base64Url = token.split('.')[1];
  const base64 = base64Url.replaceAll('-', '+').replaceAll('_', '/');
  const jsonPayload = decodeURIComponent(
    [...atob(base64)]
      .map((c) => {
        return `%${`00${(c.codePointAt(0) as any).toString(16)}`.slice(-2)}`;
      })
      .join(''),
  );

  return JSON.parse(jsonPayload);
}
export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: AuthApi.LoginParams,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;

    try {
      loginLoading.value = true;
      const { access_token: accessToken, refresh_token: refreshToken } =
        await authApi.loginApi(params);
      // jwt.decode(accessToken);

      const { user_name } = parseJWT(accessToken);
      const { id, username, rootCatalog, email, avatar } =
        JSON.parse(user_name);
      storageManager.setItem('userId', id);
      storageManager.setItem('username', username);
      storageManager.setItem('rootCatalog', rootCatalog);
      storageManager.setItem('email', email);
      storageManager.setItem('avatar', avatar);

      // 如果成功获取到 accessToken
      if (accessToken) {
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(accessToken);
        accessStore.setRefreshToken(refreshToken);
        // 获取用户信息并存储到 accessStore 中
        const [fetchUserInfoResult, accessCodes] = await Promise.all([
          fetchUserInfo(id),
          authApi.getAccessCodesApi(),
        ]);

        userInfo = fetchUserInfoResult;

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
        }
        if (userInfo?.userName) {
          ElNotification({
            message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.userName}`,
            title: $t('authentication.loginSuccess'),
            type: 'success',
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  // 注册
  async function register(params: AuthApi.RegisterParams) {
    try {
      await authApi.registerApi(params);
    } catch {
      // 不做任何处理
    }
  }

  async function logout(redirect: boolean = true) {
    try {
      await authApi.logoutApi();
    } catch {
      // 不做任何处理
    }
    await logoutWithoutApi(redirect);
  }

  /**
   * 不调用 logoutApi 的退出登录（用于双token过期重新认证时）
   * @param redirect 是否重定向
   */
  async function logoutWithoutApi(redirect: boolean = true) {
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo(id: string) {
    let userInfo: null | UserInfo = null;
    userInfo = await userApi.getUserInfo(id);
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    logoutWithoutApi,
    register,
  };
});
